import logging
from configparser import DuplicateOptionError
from logging.config import dictConfig
from flask import Flask
from ding import tools, data
from ding.views import ding
from apscheduler.schedulers.background import BackgroundScheduler
from pyfiglet import Figlet

""" 日志格式配置 """
try:
    dictConfig({
        'version': 1,
        'formatters': {'default': {
            'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
        }},
        'handlers': {'wsgi': {
            'class': 'logging.StreamHandler',
            'stream': 'ext://flask.logging.wsgi_errors_stream',
            'formatter': 'default'
        }},
        'root': {
            'level': tools.cf_connect('settings', 'log_level'),
            'handlers': ['wsgi']
        }
    })
except DuplicateOptionError as e:
    logging.error(f"{e}: 配置文件有重复选项!")


class Config(object):
    SCHEDULER_API_ENABLED = True
    SCHEDULER_TIMEZONE = 'Asia/Shanghai'


def create_app():
    """
    路由初始化
    """
    app = Flask('ding')
    register_blueprints(app)
    task()
    initialize()
    return app


def register_blueprints(app):
    """
    模块注册
    """
    app.register_blueprint(ding)


def generate_ascii_art(text, font="standard"):
    """
    字符串图案初始化
    :param text:
    :param font:
    :return:
    """
    fig = Figlet(font=font)
    ascii_art = fig.renderText(text)
    print(ascii_art)


def initialize():
    """
    系统初始化
    """
    generate_ascii_art("Ding-Talk", font="block")
    if data.db_status():
        data.es_init()
    else:
        logging.warning('历史告警存储功能未启用！')
    logging.info('访问端口为 0.0.0.0:5000，ding-talk已启动...')


def task():
    """
    每周一上午9点推送上周告警情况
    :return:
    """
    status = tools.cf_connect('settings', 'weekly_task')
    if status in 'enable':
        scheduler = BackgroundScheduler(daemon=True)
        scheduler.add_job(tools.weekly_task, 'cron', day_of_week='mon', hour=9, minute=0)
        scheduler.start()
    else:
        logging.info("每周任务未启用")
